import React, { useState, useEffect } from 'react';
import { Attendance, studentOptions, classOptions, statusOptions, validateAttendance } from '../types';

interface AddEditAttendanceModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (attendance: Attendance) => void;
  initialData?: Attendance | null;
  isEditing: boolean;
}

const AddEditAttendanceModal: React.FC<AddEditAttendanceModalProps> = ({
  isOpen,
  onClose,
  onSave,
  initialData,
  isEditing,
}) => {
  const [formData, setFormData] = useState<Omit<Attendance, 'id'>>({
    date: '',
    studentId: '',
    studentName: '',
    classId: '',
    className: '',
    status: '',
    remark: '',
    createdBy: localStorage.getItem('currentUser') || 'system',
    createdAt: new Date().toISOString(),
    updatedBy: localStorage.getItem('currentUser') || 'system',
    updatedAt: new Date().toISOString(),
  });

  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  // 初始化表单数据
  useEffect(() => {
    if (isOpen) {
      if (isEditing && initialData) {
        setFormData({
          date: initialData.date,
          studentId: initialData.studentId,
          studentName: initialData.studentName,
          classId: initialData.classId,
          className: initialData.className,
          status: initialData.status,
          remark: initialData.remark || '',
          createdBy: initialData.createdBy || localStorage.getItem('currentUser') || 'system',
          createdAt: initialData.createdAt || new Date().toISOString(),
          updatedBy: localStorage.getItem('currentUser') || 'system',
          updatedAt: new Date().toISOString(),
        });
      } else {
        // 默认设置为今天的日期
        const today = new Date().toISOString().split('T')[0];
        setFormData({
          date: today,
          studentId: '',
          studentName: '',
          classId: '',
          className: '',
          status: 'present',
          remark: '',
          createdBy: localStorage.getItem('currentUser') || 'system',
          createdAt: new Date().toISOString(),
          updatedBy: localStorage.getItem('currentUser') || 'system',
          updatedAt: new Date().toISOString(),
        });
      }
      setErrors({});
    }
  }, [isOpen, isEditing, initialData]);

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));

    // 当学生ID改变时，自动更新学生姓名和班级信息
    if (name === 'studentId') {
      const selectedStudent = studentOptions.find(student => student.value === value);
      if (selectedStudent) {
        const selectedClass = classOptions.find(cls => cls.value === selectedStudent.classId);
        setFormData(prev => ({
          ...prev,
          studentName: selectedStudent.label,
          classId: selectedStudent.classId,
          className: selectedClass?.label || '',
        }));
      } else {
        setFormData(prev => ({
          ...prev,
          studentName: '',
          classId: '',
          className: '',
        }));
      }
    }

    // 清除该字段的错误
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 处理保存操作
  const handleSave = () => {
    // 验证表单数据
    const validation = validateAttendance(formData);
    
    if (!validation.isValid) {
      // 转换错误数组为对象，便于在表单中显示
      const errorObj: { [key: string]: string } = {};
      validation.errors.forEach(error => {
        if (error.includes('日期')) errorObj.date = error;
        if (error.includes('学生')) errorObj.studentId = error;
        if (error.includes('班级')) errorObj.classId = error;
        if (error.includes('状态')) errorObj.status = error;
      });
      setErrors(errorObj);
      return;
    }

    // 创建考勤记录对象，包含唯一ID
    const attendance: Attendance = {
      ...formData,
      id: isEditing && initialData ? initialData.id : `attendance-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    };

    // 调用保存回调
    onSave(attendance);
    
    // 重置表单
    setFormData({
      date: '',
      studentId: '',
      studentName: '',
      classId: '',
      className: '',
      status: 'present',
      remark: '',
      createdBy: localStorage.getItem('currentUser') || 'system',
      createdAt: new Date().toISOString(),
      updatedBy: localStorage.getItem('currentUser') || 'system',
      updatedAt: new Date().toISOString(),
    });
    setErrors({});
  };

  // 处理模态框关闭
  const handleClose = () => {
    setFormData({
      date: '',
      studentId: '',
      studentName: '',
      classId: '',
      className: '',
      status: 'present',
      remark: '',
      createdBy: localStorage.getItem('currentUser') || 'system',
      createdAt: new Date().toISOString(),
      updatedBy: localStorage.getItem('currentUser') || 'system',
      updatedAt: new Date().toISOString(),
    });
    setErrors({});
    onClose();
  };

  // 如果模态框未打开，则不渲染
  if (!isOpen) return null;

  return (
    <div className="modal-overlay">
      <div className="modal-content">
        <div className="modal-header">
          <h2 className="modal-title">{isEditing ? '编辑考勤记录' : '添加考勤记录'}</h2>
          <button className="modal-close" onClick={handleClose}>&times;</button>
        </div>
        <div className="modal-body">
          <div className="form-group">
            <label htmlFor="date">考勤日期 *</label>
            <input
              type="date"
              id="date"
              name="date"
              value={formData.date}
              onChange={handleInputChange}
              max={new Date().toISOString().split('T')[0]} // 不允许选择未来日期
            />
            {errors.date && <div className="form-error">{errors.date}</div>}
          </div>

          <div className="form-group">
            <label htmlFor="studentId">学生 *</label>
            <select
              id="studentId"
              name="studentId"
              value={formData.studentId}
              onChange={handleInputChange}
            >
              <option value="">请选择学生</option>
              {studentOptions.map(student => (
                <option key={student.value} value={student.value}>
                  {student.label} (ID: {student.value})
                </option>
              ))}
            </select>
            {errors.studentId && <div className="form-error">{errors.studentId}</div>}
          </div>

          {formData.studentName && (
            <div className="form-group">
              <label>学生姓名</label>
              <input
                type="text"
                value={formData.studentName}
                readOnly
                style={{ backgroundColor: '#f5f5f5', cursor: 'not-allowed' }}
              />
            </div>
          )}

          <div className="form-group">
            <label htmlFor="status">考勤状态 *</label>
            <select
              id="status"
              name="status"
              value={formData.status}
              onChange={handleInputChange}
            >
              {statusOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
            {errors.status && <div className="form-error">{errors.status}</div>}
          </div>

          <div className="form-group">
            <label htmlFor="remark">备注</label>
            <textarea
              id="remark"
              name="remark"
              value={formData.remark}
              onChange={handleInputChange}
              placeholder="请输入备注信息（可选）"
              rows={3}
            />
          </div>
        </div>
        <div className="modal-footer">
          <button className="btn-secondary" onClick={handleClose}>取消</button>
          <button className="btn-primary" onClick={handleSave}>
            {isEditing ? '更新' : '保存'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AddEditAttendanceModal;